package com.dave.gd.core.contants;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;

import com.dave.gd.config.OnleduConstant;
import com.dave.gd.core.shiro.ShiroUser;

public class BaseConstans {
    /**  
     * 函数功能说明 TODO:获取UUID生成的主键
     * Administrator修改者名字
     * 2013-5-8修改日期
     * 修改内容
     * @Title: getPrimaryKeyByUUID 
     * @param @return    设定文件 
     * @return String    返回类型 
     * @throws 
     */
     public static String getPrimaryKeyByUUID(){
         return UUID.randomUUID().toString();
     }  
     /**  
     * 函数功能说明 TODO:获取当前登录用户实体类
     * Administrator修改者名字
     * 2013-5-10修改日期
     * 修改内容
     * @Title: getCurrendUser 
     * @Description: TODO:
     * @param @return    设定文件 
     * @return Users    返回类型 
     * @throws 
     */
     public static ShiroUser getCurrendUser(){
         Subject subject=SecurityUtils.getSubject();
         return (ShiroUser)subject.getSession().getAttribute(OnleduConstant.SHIRO_USER);
     }  
     
     
     public static String[] getFiledName(Object o )
     {
         try
         {
             Field[] fields = o.getClass().getDeclaredFields();
             String[] fieldNames = new String[fields.length];
             for (int i = 0; i < fields.length; i++)
             {
                 fieldNames[i] = fields[i].getName();
             }
             return fieldNames;
         } catch (SecurityException e)
         {
             e.printStackTrace();
         }
         return null;
     }
     
     public static Object getFieldValueByName(String fieldName, Object o)    
     {       
        try    
        {       
            String firstLetter = fieldName.substring(0, 1).toUpperCase();       
            String getter = "get" + firstLetter + fieldName.substring(1);       
            Method method = o.getClass().getMethod(getter, new Class[] {});       
            Object value = method.invoke(o, new Object[] {});       
            return value;       
        } catch (Exception e)    
        {       
            System.out.println("属性不存在");       
            return "";       
        }       
     }  
     
       public static HashMap<String, Method> ConverBean(Class<?> drbean) {  
             Class<?> stopClass = null;  
             // 存放class信息  
             BeanInfo drbeaninfo = null;  
             // 存放属性信息  
             PropertyDescriptor[] props;  
             HashMap<String, Method> map = new HashMap<String, Method>();  
             try {  
                 // 获取class中得属性方法信息  
                 drbeaninfo = Introspector.getBeanInfo(drbean, stopClass);  
                 // 把class中属性放入PropertyDescriptor数组中  
                 props = drbeaninfo.getPropertyDescriptors();  
                 for (int i = 0; i < props.length; i++) {  
                     // 获取属性所对应的set方法  
                     Method setMethod = props[i].getWriteMethod();  
                     // 判断属性是否有set方法 如果有放入map<属性名，set方法>中  
                     if (setMethod != null) {  
                         String field = props[i].getName().toLowerCase();  
                         map.put(field, setMethod);  
                     }  
                 }  
             } catch (IntrospectionException e) {  
                 // TODO Auto-generated catch block  
                 e.printStackTrace();  
             }  
             return map;  
         }
     
     /**  
     * 函数功能说明 TODO:获取客户端ip地址
     * Administrator修改者名字
     * 2013-6-19修改日期
     * 修改内容
     * @Title: getIpAddr 
     * @Description: 
     * @param @return    设定文件 
     * @return String    返回类型 
     * @throws 
     */
     public static String getIpAddr() {
            HttpServletRequest request=ServletActionContext.getRequest();
            String ip = request.getHeader("x-forwarded-for");
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            return ip;
        } 
     
     
     private static final int BUFFER_SIZE = 16 * 1024;
      public static void copy(File src, String fullSavePath) {
             InputStream in = null; 
             OutputStream out = null; 
             File newFile=new File(fullSavePath);
             try { 
                 in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); 
                 out = new BufferedOutputStream(new FileOutputStream(newFile), 
                         BUFFER_SIZE); 
                 byte[] buffer = new byte[BUFFER_SIZE]; 
                 int len = 0; 
                 while ((len = in.read(buffer)) > 0) { 
                     out.write(buffer, 0, len); 
                 } 
                 out.flush();
             } catch (Exception e) { 
                 e.printStackTrace(); 
             } finally { 
                 if (null != in) { 
                     try { 
                         in.close(); 
                     } catch (IOException e) { 
                         e.printStackTrace(); 
                     } 
                 } 
                 if (null != out) { 
                     try { 
                         out.close(); 
                     } catch (IOException e) { 
                         e.printStackTrace(); 
                     } 
                 } 
             } 
         }
      public static String BASE_PATH =System.getProperty("bs_onledu");
      public static String dbBackUp()
         {
             //生成临时备份文件
             SimpleDateFormat sd=new SimpleDateFormat("yyyyMMddHHmmss");
             String fineName="dbBackUp-"+sd.format(new Date());
             String sqlName=fineName+OnleduConstant.FILE_SUFFIX_SQL;
             String pathSql=BASE_PATH+"attachment"+File.separator+"dbBackUp";
             try {
                 File filePathSql = new File(pathSql);
                 if(!filePathSql.exists()){
                     filePathSql.mkdir();
                 }
                 StringBuffer sbs = new StringBuffer();
                 sbs.append("mysqldump ");
                 sbs.append("-h 192.168.110.10 ");
                 sbs.append("--user=root");
                 sbs.append(" --password=root");
                 sbs.append(" --lock-all-tables=true ");
                 sbs.append("--result-file="+pathSql+File.separator);
                 sbs.append(sqlName+" ");
                 sbs.append(" --default-character-set=utf8 ");
                 sbs.append("ERP");
                 Runtime runtime = Runtime.getRuntime();
                 Process child = runtime.exec(sbs.toString());
                 //读取备份数据并生成临时文件
                 InputStream in = child.getInputStream();
                 @SuppressWarnings("resource")
                 OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(pathSql), "utf8");
                 BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf8"));
                 String line=reader.readLine();
                 while (line != null) {
                         writer.write(line+"\n");
                         line=reader.readLine();
                  }
                  writer.flush();
             } catch (Exception e) {
                 
             }
             return sqlName;
         }
}
